package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.UserBean;
import dao.UserDAO;

/**
 * Servlet implementation class AccountServlet
 * 
 * @author Sander Meijer & Stijn Kliemesch
 * 
 */
public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AccountServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 * Used for logging out. 
	 * Requires parameter "action" with value "logout".
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");

		if (action.equalsIgnoreCase("logout")) {
			request.getSession().invalidate();
			response.sendRedirect("/veilingsite-webtech/index.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 * Used for logging in, registering and updating.
	 * Requires parameter "action" with one of the following values:
	 * -"login"
	 * -"register"
	 * -"update"
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String action = request.getParameter("action");

		if (action.equalsIgnoreCase("login")) {
			handleLogin(request, response);
		} else if (action.equalsIgnoreCase("register")) {
			handleRegister(request, response);
		} else if (action.equalsIgnoreCase("update")){
			handleUpdate(request, response);
		}
	}

	/**
	 * handles the login of users
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void handleLogin(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		RequestDispatcher dispatcher = null;
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		
		UserBean userBean = UserDAO.getUserByUsername(name);
		
		String errorUrl = "/WEB-INF/login.jsp?error=";
		String url = "";
		
		//Decide whether to forward to the login page and provide the information on what went wrong with logging in
		//or when succesfully logged in forward to the home page
		if(name.equals("")) {//no username entered
			url = errorUrl + "combination";
		} else if(password.equals("")) {//no password entered
			url = errorUrl + "password";
		} else if(userBean == null) {//user does not exist
			url = errorUrl + "combination";
		} else if(password.equals(userBean.getPassword())){
			request.getSession().setAttribute("loggedIn", true);
			request.getSession().setAttribute("userID", userBean.getUserID());
			request.getSession().setAttribute("userName", userBean.getUserName());
			url = "/WEB-INF/home.jsp?showmenu=true";
		} else { //user exists but wrong password entered
			url = errorUrl + "combination";
		}
		
		dispatcher = request.getRequestDispatcher(response.encodeURL(url));
		dispatcher.forward(request, response);
	}
	
	/**
	 * Handles the updating of user information (only password)
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void handleUpdate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String password = request.getParameter("password");
		String newPassword = request.getParameter("newPassword");
		String newPasswordRep = request.getParameter("newPasswordRepeat");
		RequestDispatcher dispatcher = null;
		 
		int userID = (Integer) request.getSession().getAttribute("userID");
		
		UserBean userBean = UserDAO.getUserByID(userID);
		
		String errorURL = "/WEB-INF/accountinfo.jsp?error=";
		String url = "";
		
		//Decide whether to forward to the accountinfo page and provide the information on what went wrong with changing the password
		//Or change the password and forward to the accountinfo page
		if(userBean.getPassword().equals(password)){ //password correct
			if(newPassword.equals(newPasswordRep) && !newPassword.equals("")){ //new password has been filled in correctly twice
				UserDAO.updateUserByID(newPassword, userID);
				url = "/WEB-INF/accountinfo.jsp";
			} else { //new password has not been filled in correctly twice
				url = errorURL + "notEqualError";
			}
		} else { //password incorrect
			url = errorURL + "oldPassError";
		}
		
		dispatcher = request.getRequestDispatcher(response.encodeRedirectURL(url));
		dispatcher.forward(request, response);
	}
	
	/**
	 * handles the registration of new users
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void handleRegister(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		RequestDispatcher dispatcher = null;
		
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		String passwordrepeat = request.getParameter("passwordrepeat");
		
		String errorURL = "/WEB-INF/register.jsp?error=";
		String url = "";
		
		//Decide whether to forward to the register page and provide the information on what went wrong with registering
		//Or register and login (and subsequently forward to the home page)
		if(name.equals("") || UserDAO.getUserExists(name)) {//name is empty or user already exists
			url = errorURL + "name";
		} else if(password.equals("")) { //password is empty
			url = errorURL + "password";
		} else if(!password.equals(passwordrepeat)) { //password isnt filled in correctly twice
			url = errorURL + "passwordrepeat";
		} else { //register succes and login
			UserDAO.createNewUser(name, password);
			handleLogin(request, response);
		}
		if(!url.equals("")) {
			dispatcher = request.getRequestDispatcher(response.encodeURL(url));
			dispatcher.forward(request, response);
		}
	}
	
}
